%clc
%clear
tic;
%{
EEG_pretreatment(main_folder_path, in_periodization_path, end_subject_num, ...
    band_pass_start_freq,band_pass_end_freq,notch_start_freq,notch_end_freq)
main_folder_path：edf文件地址
in_periodization_path：分期信息表地址
end_subject_num：从01开始 需要到第几个患者结束
band_pass_start_freq：带通滤波起始频率
band_pass_end_freq：带通滤波结束频率
notch_start_freq：陷波起始频率
notch_end_freq：陷波结束频率
%}
main_folder_path = 'C:\Users\liwan\Desktop\EDF_File\CHBMIT_reduced';
in_periodization_path = 'C:\Users\liwan\Desktop\MATLAB_File\periodization\periodization_code\CHBMIT_seizures_new_15_1.xlsx';
end_subject_num = 24;
band_pass_start_freq=1;
band_pass_end_freq=100;
notch_start_freq=58;
notch_end_freq=62;
%[negative_path,positive_path]=EEG_pretreatment(main_folder_path,in_periodization_path,end_subject_num, ...
                                              %band_pass_start_freq,band_pass_end_freq,notch_start_freq,notch_end_freq);
%片段长度
target_frame=4;
%采样率
sampling_rate=256;
%样本组数量
sampling_counts =10; 
%样本数量
num_samples=10;
%经过滤波后的mat文件地址
%negative_path='\\192.168.0.186\g$\MATLAB_File\sampling_code\CHB_original_15_1_ictal\test\negative';
%positive_path='\\192.168.0.186\g$\MATLAB_File\sampling_code\CHB_original_15_1_ictal\test\positive';

% 从外部文件加载文件权重
positive_mat_files = dir(fullfile(positive_path, '*.mat'));
positive_data_matrices = cell(1, numel(positive_mat_files));
parfor file_index = 1:numel(positive_mat_files)
    file_path = fullfile(positive_path, positive_mat_files(file_index).name);
    loaded_data = load(file_path);
    positive_data_matrices{file_index} = loaded_data.data;
end
negative_mat_files = dir(fullfile(negative_path, '*.mat'));
negative_data_matrices = cell(1, numel(negative_mat_files));
parfor file_index = 1:numel(negative_mat_files)
    file_path = fullfile(negative_path, negative_mat_files(file_index).name);
    loaded_data = load(file_path);
    negative_data_matrices{file_index} = loaded_data.data;
end

file_weights_data=EEG_positive_file_weight_calculate(in_periodization_path);
EEG_weight_sampling(positive_data_matrices,negative_data_matrices,file_weights_data, ...
                      positive_path,negative_path, ...
                      target_frame,sampling_rate,num_samples,sampling_counts)  
% 定义循环次数
numIterations = 10;
tic;
for i = 1:numIterations
    
    disp(['正在执行第 ', num2str(i), ' 次循环...']);
    % 生成文件夹路径
    negative_folder = sprintf('./negative_%d_samples_%d',num_samples,i);
    positive_folder = sprintf('./positive_%d_samples_%d',num_samples,i);
    
    % 加载数据
    negative_data = loadDataFromFolder(negative_folder);
    positive_data = loadDataFromFolder(positive_folder);
    
    %% 原始数据合并+标签+乱序 生成数据集后可注释
    data_combined_shuffled = combineAndShuffleData(negative_data,positive_data);
    data_filename = sprintf('CHBMIT_raw_data_%d_%d.mat',num_samples, i);
    save(data_filename,'data_combined_shuffled');
    
    %% 生成数据集后可采用下面的代码读取
    %{
    raw_data_folder = sprintf('./raw_data_%d/raw_data_%d_%d.mat',num_samples,num_samples, i);
    load(raw_data_folder);
    %}

    %原始数据集
    raw_data = data_combined_shuffled(:,1);
    %对应标签
    labels = cell2mat(data_combined_shuffled(:,2));
    %% 合并样本集时频域提取 在此修改特征
    [time_channel_features, time_total_features] = EEG_time_feature_extraction(raw_data);
    
    [frequency_channel_features, frequency_total_features] = EEG_frequency_feature_extraction(raw_data,sampling_rate,1024,1,70);
    %[frequency_channel_features, frequency_total_features] = EEG_wavelet_feature_extraction(positive_data,256,'db4',5);
    %特征结果
    total_X = mergeTimeFreqFeatures(time_channel_features, time_total_features,frequency_channel_features, frequency_total_features);

    combined_features =[total_X,labels];
    % 特征+标签集存储
    features_filename = sprintf('classification_results_basic_%d_%d.mat',num_samples, i);
    save(features_filename,'combined_features');
    %代码执行时间
    elapsedTime = toc;
    disp(['执行时间：', num2str(elapsedTime), ' 秒']);
end


function mergedArray =mergeTimeFreqFeatures(time_channel_features, time_total_features,frequency_channel_features, frequency_total_features) 
    % 初始化合并后的特征矩阵
    numSamples = length(time_channel_features);
    
    % 获取时域特征的维度
    timeFeatureSize = size(cell2mat(time_channel_features{1}));
    %{
    % 遍历所有时域特征，确保维度一致
    for i = 2:length(time_channel_features)
        if ~isequal(size(cell2mat(time_channel_features{i})), timeFeatureSize)
            error('时域特征的维度不一致！');
        end
    end
    %}
    % 获取频域特征的维度
    freqFeatureSize = size(cell2mat(frequency_channel_features{1}));
    %{
    % 遍历所有频域特征，确保维度一致
    for i = 2:length(frequency_channel_features)
        if ~isequal(size(cell2mat(frequency_channel_features{i})), freqFeatureSize)
            error('频域特征的维度不一致！');
        end
    end
    %}
    timeChannels = timeFeatureSize(1);
    freqChannels = freqFeatureSize(1);
    % 选择有值的通道数
    commonChannels = max(timeChannels, freqChannels); % 处理单特征情况
    % 初始化合并后的特征矩阵
    mergedFeatures = zeros(numSamples, commonChannels, timeFeatureSize(2) + freqFeatureSize(2));
    % 循环遍历每个样本
    for i = 1:length(time_channel_features)
        % 获取时域特征和频域特征
        timeChannelDomainFeatures = cell2mat(time_channel_features{i});
        freqChannelDomainFeatures = cell2mat(frequency_channel_features{i});
        % 将时域特征和频域特征水平拼接

        combinedFeatures = [timeChannelDomainFeatures, freqChannelDomainFeatures];
        % 将当前样本的特征添加到合并后的特征矩阵中
        % 仅取前18个特征
        mergedFeatures(i,:,:) =combinedFeatures(1:18, :);
    end
    combinedFeatures  = reshape(mergedFeatures, size(mergedFeatures, 1), []);
    % 初始化存储合并结果的数组
    mergedArray = cell(length(time_total_features), 1);
    
    % 循环遍历每个样本
    for i = 1:length(time_total_features)
        % 获取当前迭代的 combinedFeatures 的第 i 行
        currentCombinedFeatures = combinedFeatures(i,:);
        
        % 将 time_total_feature 和 frequency_total_feature 转换为 double 类型
        timeTotalDomainFeatures = double(cell2mat(time_total_features{i}));
        freqTotalDomainFeatures = double(cell2mat(frequency_total_features{i}));
        
        % 将当前迭代的特征组合成一个行向量
        combinedTotalFeatures = [timeTotalDomainFeatures, freqTotalDomainFeatures];
        
        % 将当前迭代的结果与 combinedFeatures 合并
        mergedResult = [currentCombinedFeatures, combinedTotalFeatures];
        
        % 将当前迭代的结果存储到存储数组中
        mergedArray{i} = mergedResult;
    end
    % 将 mergedArray 转换为数组类型
    mergedArray = cell2mat(mergedArray);

end

function  data_combined_shuffled = combineAndShuffleData(negative_data,positive_data)
   
    labels_negative = 2*ones(size(negative_data, 1), 1);
    labels_positive = ones(size(positive_data, 1), 1);

    %原始数据与特征整合
    data_negative = [negative_data, num2cell(labels_negative)];
    data_positive = [positive_data, num2cell(labels_positive)];

    %正负样本整合
    data_combined=[data_negative;data_positive];
    %随机打乱索引
    idx_random = randperm(size(data_combined, 1));
    data_combined_shuffled = data_combined(idx_random, :);
end

function data = loadDataFromFolder(folderPath)
    % 获取文件夹下所有 .mat 文件
    matFiles = dir(fullfile(folderPath, '*.mat'));

    % 初始化单元格数组用于存储所有数据
    data = {};

    % 循环遍历每个 .mat 文件并加载数据
    for j = 1:length(matFiles)
        filePath = fullfile(folderPath, matFiles(j).name);
        loadedData = load(filePath);
        fields = fieldnames(loadedData);
        data = [data; loadedData.(fields{1})];
    end
end